
package bibliotheque.server;

import bibliotheque.wave.WaveAction;
import bibliotheque.wave.WaveAgent;

public class StopAction extends WaveAction {
    
    public StopAction() {
        
    }
    
    public void PropagateAfter(WaveAgent agent) throws Exception {
        final Server server;
        Thread thread;
        if(agent instanceof Server) {
            server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.SUBSCRIBING) throw new Exception("Stop failed cause server state is subscribing.");
                if(server.state == Server.State.STOPPING) throw new Exception("Stop failed cause server state is stopping.");
                if(server.state == Server.State.STOP) throw new Exception("Stop failed cause server state is stopped.");
                
                server.timertask_hellotimeout.cancel();
                
                if(server.state == Server.State.STARTING) {
                    server.state = Server.State.STOP;
                    server.StateChanged(server.state.toString());
                } else {
                    //TODO prevenir les client
                    //TODO fermer toutes les transaction en local
                    server.state = Server.State.STOP;
                    server.StateChanged(server.state.toString());
                }
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
        }
    }
    
    public void GlobalEnd(WaveAgent agent) throws Exception {
        Server server;
        if(agent instanceof Server) {
            server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.SUBSCRIBING) throw new Exception("Stop failed cause server state is subscribing.");
                if(server.state == Server.State.STARTING) throw new Exception("Stop failed cause server state is starting");
                if(server.state == Server.State.START) throw new Exception("Stop failed cause server state is started");
                if(server.state == Server.State.STOPPING) throw new Exception("Stop failed cause server state is stopping");
                try {
                    server.name_server.Stopped();
                } catch (Exception ex) {
                    throw new Exception("Stop failed cause the name_server returns an error.");
                }
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
        }
    }
}
